from logging import getLogger

from solr import SolrConnection

from meercat.ui.client import parser
from meercat.ui.client.rest import Rest
from meercat.ui.client.utils import unicodeParameterEncoding



log = getLogger('meercat.ui.client.client')

class Client(object):
    def __init__(self, solrParams, restParams, **kwargs):
        kwargs.setdefault('solrConnector', SolrConnection)
        kwargs.setdefault('restConnector', Rest)
        
        kwargs.setdefault('solrDefaultParams', {})
        kwargs.setdefault('solrForcedParams', {})
        
        kwargs.setdefault('solrResponseParser', parser.solr_response)
        kwargs.setdefault('restResponseParser', parser.rest_response)
        
        if not issubclass(kwargs['solrConnector'], SolrConnection):
            raise ValueError('solrConnector must be a subclass of solrpy\'s '
                             'SolrConnection (solr.SolrConnection)')
        
        if not callable(kwargs['solrResponseParser']):
            raise ValueError('solrResponseParser must be callable')
        
        if not callable(kwargs['restResponseParser']):
            raise ValueError('restResponseParser must be callable')
        
        if not isinstance(kwargs['solrDefaultParams'], dict):
            raise ValueError('solrDefaultParams must be a dictionary')
        
        if not isinstance(kwargs['solrForcedParams'], dict):
            raise ValueError('solrForcedParams must be a dictionary')
        
        if not isinstance(solrParams, dict):
            raise ValueError('solrParams must be a dictionary')
        
        if not isinstance(restParams, dict):
            raise ValueError('restParams must be a dictionary')
        
        try:
            kwargs['solrConnector'](**solrParams)
        except Exception, e:
            log.exception('Invalid solr parameters: %s' % (str(solrParams)),)
            raise e
        
        try:
            kwargs['restConnector'](**restParams)
        except Exception, e:
            log.exception('Invalid rest parameters: %s' % (str(restParams)),)
            raise e
        
        self.solrParams = solrParams
        self.restParams = restParams
        
        for key in ('solrConnector', 'solrDefaultParams', 'solrForcedParams',
                    'solrResponseParser','restResponseParser', 'restConnector',):
            setattr(self, key, kwargs.pop(key))
        
    def query(self, **params):
        qp = {}
        # Add all default parameters in
        qp.update(self.solrDefaultParams)
        # Add user code submitted parameters
        qp.update(params)
        # Add forced query parameters
        qp.update(self.solrForcedParams)
        qp = unicodeParameterEncoding(qp)
        
        connection = self.solrConnector(**self.solrParams)
        log.debug('Solr connection created')
        
        response = connection.query(**qp)
        log.debug('Solr queried: %s\n%s' % (str(qp),str(response),))
        return self.solrResponseParser(response) 
    
    def getResource(self, identifier):
        connection = self.restConnector(**self.restParams)
        log.debug('Rest connection created')
        response = connection.get(identifier)
        log.debug('Rest response received')
        return self.restResponseParser(response)
        